import { defineStore } from "pinia";
import { ref } from "vue";
import api from "@/utils/api";

export const useUserStore = defineStore("user", () => {
  const user = ref(null);
  const token = ref(localStorage.getItem("token"));

  // 登录
  const login = async (credentials) => {
    try {
      const response = await api.post("/auth/login", credentials);
      const { token: newToken, user: userData } = response.data;

      token.value = newToken;
      user.value = userData;

      localStorage.setItem("token", newToken);

      return userData;
    } catch (error) {
      throw new Error(error.response?.data?.error || "登录失败");
    }
  };

  // 退出登录
  const logout = async () => {
    token.value = null;
    user.value = null;
    localStorage.removeItem("token");
  };

  // 验证令牌
  const verifyToken = async () => {
    if (!token.value) return false;

    try {
      const response = await api.get("/auth/verify");
      user.value = response.data.user;
      return true;
    } catch (error) {
      // 令牌无效，清除本地存储
      token.value = null;
      user.value = null;
      localStorage.removeItem("token");
      return false;
    }
  };

  // 检查是否已登录
  const isLoggedIn = () => {
    return !!token.value && !!user.value;
  };

  // 检查是否为管理员
  const isAdmin = () => {
    return user.value?.role === "admin";
  };

  return {
    user,
    token,
    login,
    logout,
    verifyToken,
    isLoggedIn,
    isAdmin,
  };
});
